package validation

import (
	"context"
	"errors"
	"gorm.io/gen"
	"gorm.io/gorm"
	"mall_frontend_api/biz/dal"
	"mall_frontend_api/biz/lib/biz_error"
	"mall_frontend_api/biz/model"
	"mall_frontend_api/biz/model/cart"
)

func CheckAddCart(ctx context.Context, req *cart.AddCartRequest) error {
	_, err := dao.ProductDAO.GetInfoByID(ctx, req.GetProductID())
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return biz_error.NewBizError().SetLogMessage("dal GetProductInfoByID").SetServerErrorMessage(err.Error())
	}

	if errors.Is(err, gorm.ErrRecordNotFound) {
		return biz_error.NewBizError().SetLogMessage("dal GetProductInfoByID").SetBadRequestErrorMessage("The product has been taken down, please add it again")
	}

	if req.GetNumber() <= 0 {
		return biz_error.NewBizError().SetLogMessage("number error").SetBadRequestErrorMessage("The quantity of the product is incorrect")
	}

	productItemList, err := dao.ProductItemDAO.GetList(ctx, []gen.Condition{dal.ProductItem.ProductID.Eq(req.ProductID)}, 0, 0)
	if err != nil {
		return biz_error.NewBizError().SetLogMessage("dal GetProductItemList").SetServerErrorMessage(err.Error())
	}

	var sku bool
	for _, item := range productItemList {
		if item.SkuID == req.GetSKUID() {
			sku = true
		}
	}
	if !sku {
		return biz_error.NewBizError().SetLogMessage("dal GetProductItemList").SetBadRequestErrorMessage("The SKU of the product does not exist, please add it again")
	}
	return nil
}

func CheckUpdateCart(ctx context.Context, req *cart.UpdateCartRequest, userInfo *model.UserInfo) error {
	cartInfo, err := dao.CartDAO.GetInfoByID(ctx, req.GetID())
	if err != nil {
		return biz_error.NewBizError().SetLogMessage("dal GetCartInfoByID").SetServerErrorMessage(err.Error())
	}

	if cartInfo.UserID != userInfo.ID {
		return biz_error.NewBizError().SetLogMessage("userInfo not match").SetServerErrorMessage("Authentication failed")
	}

	if req.GetNumber() <= 0 {
		return biz_error.NewBizError().SetLogMessage("number error").SetBadRequestErrorMessage("The quantity of the product is incorrect")
	}

	return nil
}

func CheckDeleteCart(ctx context.Context, req *cart.DeleteCartRequest, userInfo *model.UserInfo) error {
	cartMap, err := dao.CartDAO.MGet(ctx, req.GetIDs())
	if err != nil {
		return biz_error.NewBizError().SetLogMessage("dal GetCartInfoByID").SetServerErrorMessage(err.Error())
	}

	if len(cartMap) != len(req.GetIDs()) {
		return biz_error.NewBizError().SetLogMessage("dal 数量不匹配").SetServerErrorMessage("Authentication failed")
	}

	for _, c := range cartMap {
		if c.UserID != userInfo.ID {
			return biz_error.NewBizError().SetLogMessage("userInfo not match").SetServerErrorMessage("Authentication failed")
		}
	}

	return nil
}
